package com.jinlia.show.modules.base.system.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinlia.show.common.core.exception.MyRuntimeException;
import com.jinlia.show.modules.base.model.po.DeliveryOrderPO;
import com.jinlia.show.modules.base.model.po.OrderPO;
import com.jinlia.show.modules.base.model.query.DeliveryOrderQuery;
import com.jinlia.show.modules.base.model.vo.DeliveryOrderVO;
import com.jinlia.show.modules.base.system.entity.DeliveryOrder;
import com.jinlia.show.modules.base.system.entity.Order;
import com.jinlia.show.modules.base.system.entity.OrderItem;
import com.jinlia.show.modules.base.system.mapper.DeliveryOrderMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class DeliveryOrderMapperService extends ServiceImpl<DeliveryOrderMapper, DeliveryOrder> {


    @Autowired
    private OrderMapperService orderMapperService;
    @Autowired
    private OrderItemMapperService orderItemMapperService;
    @Autowired
    private GoodsMapperService goodsMapperService;
    @Autowired
    private IdGeneratorMapperService idGeneratorMapperService;
    @Autowired
    private OrderLogMapperService orderLogMapperService;
    @Autowired
    private ErrandOrderMapperService errandOrderMapperService;

    /**
     * @param deliveryOrder
     * @return
     */
    public Boolean add(DeliveryOrder deliveryOrder) {
        //订购单生成校验()
        Long count = this.lambdaQuery().eq(DeliveryOrder::getOrderId, deliveryOrder.getOrderId()).count();
        if (count > 0) {
            throw new MyRuntimeException("一个订单不支持两次配送!!!");
        }
        deliveryOrder.setCreateTime(null);
        deliveryOrder.setCreator(null);
        deliveryOrder.setLastUpdater(null);
        deliveryOrder.setLastUpdateTime(null);
        //反显订单状态
        return this.save(deliveryOrder);
    }

    /**
     * 待接单(支付后)
     *
     * @param deliveryOrder
     * @return
     */
    @Transactional
    public Boolean waitConfirmDeliveryOrder(DeliveryOrder deliveryOrder) {
        //添加接单人和接单时间和状态
//        deliveryOrder.setDeliveryStatus(DeliveryStatusEnum.WAIT_CONFIRM.getValue());//待接单
//        if (Objects.isNull(deliveryOrder.getId())) {
//            if (Objects.isNull(deliveryOrder.getOrderId())) {
//                throw new MyRuntimeException("更新发货单失败!!");
//            } else {
//                //通过fromOrderId更新
//                boolean update = this.lambdaUpdate()
//                        .set(DeliveryOrder::getDeliveryStatus, DeliveryStatusEnum.WAIT_CONFIRM.getValue())
//                        .eq(DeliveryOrder::getOrderId, deliveryOrder.getOrderId())
//                        .update();
//                if (!update) {
//                    throw new MyRuntimeException("接单失败,未生成收货单!!");
//                }
//            }
//        } else {
//            boolean b = this.updateById(deliveryOrder);//通过id更新
//            if (!b) {
//                throw new MyRuntimeException("接单失败,未生成收货单!!");
//            }
//        }
        return Boolean.TRUE;
    }

    /**
     * 确认接单
     *
     * @param deliveryOrder
     * @return
     */
    @Transactional
    public DeliveryOrder confirmDeliveryOrder(DeliveryOrder deliveryOrder) {
        return this.confirmDeliveryOrder(deliveryOrder, true);
    }

    /**
     * @param deliveryOrder
     * @param checkConfirm  是否校验重复接单
     * @return
     */
    @Transactional
    public DeliveryOrder confirmDeliveryOrder(DeliveryOrder deliveryOrder, Boolean checkConfirm) {
        //修改订单状态
        DeliveryOrder byIdDeliveryOrder = this.getById(deliveryOrder.getId());
//        if (!checkConfirm && !DeliveryStatusEnum.WAIT_CONFIRM.getValue().equals(byIdDeliveryOrder.getDeliveryStatus())) {
//            //兼容 + 一键
//            return byIdDeliveryOrder;
//        }
//        if (!DeliveryStatusEnum.WAIT_CONFIRM.getValue().equals(byIdDeliveryOrder.getDeliveryStatus())) {
//            //防止库存被重复占用 TODO(是否在发货时？？？？)
//            return byIdDeliveryOrder;
//        }
//        //添加接单人和接单时间和状态
//        this.lambdaUpdate()
//                .eq(DeliveryOrder::getId, deliveryOrder.getId())
//                .set(DeliveryOrder::getDeliveryStatus, DeliveryStatusEnum.MAKING.getValue()) //制作中
//                .update(new DeliveryOrder());
        //库存模式
        List<OrderItem> list = orderItemMapperService.lambdaQuery()
                .eq(OrderItem::getOrderId, byIdDeliveryOrder.getOrderId())
                .list();
        for (OrderItem item : list) {
            goodsMapperService.updateStockNum(item.getGoodsId(), -item.getGoodsNum());
        }
        return byIdDeliveryOrder;
    }


    /**
     * 配送发货
     *
     * @param deliveryOrder
     * @return
     */
    @Transactional
    public Boolean startDeliverOrder(DeliveryOrder deliveryOrder) {
//        if (deliveryOrder.getId() == null) {
//            throw new MyRuntimeException("id不能为null");
//        }
//        //添加接单人和接单时间和状态
//        DeliveryOrder byIdDeliveryOrder = this.getById(deliveryOrder.getId());
//        if (byIdDeliveryOrder.getDeliveryType().equals(DeliveryTypeEnum.OTHER_PICT.getValue())) {
//            throw new MyRuntimeException("请先选择配送方式!!!");
//        }
//        if (byIdDeliveryOrder.getDeliveryType().equals(DeliveryTypeEnum.SELF_PICT.getValue())) {
//            //堂食订单
//            this.lambdaUpdate()
//                    .eq(DeliveryOrder::getId, deliveryOrder.getId())//
//                    .set(DeliveryOrder::getDeliveryStatus, DeliveryStatusEnum.USER_CONFIRM.getValue()) //在路上
//                    .update(new DeliveryOrder());
//        } else {
//            //完成订单
//            this.lambdaUpdate()
//                    .eq(DeliveryOrder::getId, deliveryOrder.getId())//
//                    .set(DeliveryOrder::getDeliveryStatus, DeliveryStatusEnum.ON_WAY.getValue()) //在路上
//                    .update(new DeliveryOrder());
//        }
        return Boolean.TRUE;
    }

    /**
     * 配送完成(配送人确认)
     *
     * @param deliveryOrder
     * @return
     */
    @Transactional
    public Boolean okDeliveryOrder(DeliveryOrder deliveryOrder) {
//        deliveryOrder.setDeliveryStatus(DeliveryStatusEnum.ARRIVED.getValue());//已送达
        this.updateById(deliveryOrder);

        return Boolean.TRUE;
    }


    /**
     * 顾客确认
     *
     * @param deliveryOrder
     * @return
     */
    @Transactional
    public Boolean userConfirmDeliveryOrder(DeliveryOrder deliveryOrder) {
//        deliveryOrder.setDeliveryStatus(DeliveryStatusEnum.USER_CONFIRM.getValue());//待确认(顾客)
        this.updateById(deliveryOrder);
        //订单操作记录
        orderLogMapperService.addOrderLog("PS",
                deliveryOrder.getId(), "顾客收货", "订单完成");
        return Boolean.TRUE;
    }

    /**
     * 分页PO
     *
     * @param deliveryOrderQuery
     * @return
     */
    public Page<DeliveryOrderVO> getPagePO(DeliveryOrderQuery deliveryOrderQuery) {
        Page<DeliveryOrderVO> page = new Page<>(deliveryOrderQuery.getCurrent(), deliveryOrderQuery.getSize());
        Page<DeliveryOrderVO> pageVO = this.getBaseMapper().getPageVO(page, deliveryOrderQuery);
        //填充订单信息
        if (!CollectionUtils.isEmpty(pageVO.getRecords())) {
            Long[] orderIds = pageVO.getRecords().stream().map(i -> i.getOrderId()).toArray(Long[]::new);
            Map<Long, OrderPO> collect =
                    orderMapperService.getPOByIds(orderIds).stream().collect(Collectors.toMap(Order::getId, Function.identity()));
            pageVO.getRecords().forEach(i -> {
                i.setOrderPO(collect.get(i.getOrderId()));
            });

        }
        return pageVO;
    }

    public DeliveryOrderPO getDetails(Long deliveryOrderId) {
        DeliveryOrder byId = this.getById(deliveryOrderId);
        DeliveryOrderPO deliveryOrderPO = DeliveryOrderPO.fromEntity(byId);
        List<OrderPO> poByIds = orderMapperService.getPOByIds(byId.getOrderId());
        deliveryOrderPO.setOrderPO(poByIds.get(0));
        return deliveryOrderPO;
    }


    public DeliveryOrderPO getByOrderId(Long id) {
        DeliveryOrder one = this.lambdaQuery()
                .eq(DeliveryOrder::getOrderId, id)
                .last("limit 1")
                .one();
        if (one != null) {
            return  getDetails(one.getId());
        }
        return null;
    }

}
